package cn.com.dycc.sys_manage.rolesysmanagement.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.dycc.common.log.Constants;
import cn.com.dycc.common.log.SystemServiceLog;
import cn.com.dycc.sys_manage.rolesysmanagement.dao.RoleUserDao;
import cn.com.dycc.sys_manage.usersysmanagement.dao.UserDao;
import cn.com.dycc.sys_manage.usersysmanagement.entity.UserInfoAccount;

@Service("roleUserService")
@Transactional
public class RoleUserServiceImpl implements RoleUserService{
	
	@Resource(name="roleUserDao")
	private RoleUserDao roleUserDao;
	
	@Resource(name="userDao")
	private UserDao userDao;
	
	//点击增加权限，查询用户列表，给用户增加权限
	@SystemServiceLog(description=Constants.T_ROLEUSER_ADD)
	public String addListRoleUser(String role_no, String[] privIds) throws RoleUserNotFoundException {
		
//		System.out.println("privIds="+privIds);
		
		if(role_no==null||role_no.trim().isEmpty()){
			throw new RoleUserNotFoundException("请选择角色权限！");
		}
		
		//权限用户更改
		//根据角色id查询用户是否存在已分配用户
		List<String> list = roleUserDao.findUserIdByRoleNo(role_no);
		//参数map
		Map<String,Object> map = new HashMap<String,Object>();
		
		if(list.isEmpty()){
			if(privIds.length==0){
				throw new RoleUserNotFoundException("角色权限还未选择任何用户！");
			}
			map.put("privIds",privIds);
			map.put("role_no",role_no);
			int add = roleUserDao.addListRoleUser(map);
			if(add!=privIds.length){
				throw new RoleUserNotFoundException("增加失败！");
			}
		}else{
			int i = 0;
			if(privIds.length==0){
				i = roleUserDao.deleteRoleUserByRoleNo(role_no);
				if(i<=0){
					throw new RoleUserNotFoundException("增加失败！");
				}
			}else{
				i = roleUserDao.deleteRoleUserByRoleNo(role_no);
				if(i<=0){
					throw new RoleUserNotFoundException("增加失败！");
				}
				map.put("privIds",privIds);
				map.put("role_no",role_no);
				int add = roleUserDao.addListRoleUser(map);
				if(add!=privIds.length){
					throw new RoleUserNotFoundException("增加失败！");
				}
			}
			
		}
		return "增加成功！";
	}
	
	//根据角色id查询已授权用户的信息
	public List<UserInfoAccount> findUserInfoByRoleNo(String role_no) throws RoleUserNotFoundException {
		
		if(role_no==null||role_no.trim().isEmpty()){
			throw new RoleUserNotFoundException("请先选择需要查询的权限！");
		}
		List<UserInfoAccount> List = new ArrayList<UserInfoAccount>();
		
		try {
			List = roleUserDao.findUserInfoByRoleNo(role_no);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RoleUserNotFoundException("查询失败！请稍后重试");
		}
		
		return List;
	}

}
